<template>

    <transition name="fade">
        <div
            class="player-bar  flex-row"
            v-show="playList.length > 0"
        >
            <el-card class="box-card">
                <div class="container">

                    <div
                        class="avatar"
                        @click="toDetail()"
                    >
                        <img :src="currentSong.image" />
                    </div>
                    <div
                        class="info ellipsis"
                        @click="toDetail()"
                    >
                        <p class="name ">{{ currentSong.name }}</p>
                        <p class="singer flex-row ellipsis">
                            <span>{{ currentSong.singer }}</span>
                        </p>
                    </div>
                    <div class="player-btn">
                        <i
                            class="iconfont icon-prev niceshangyishou"
                            @click="prevSong"
                        ></i>
                        <i
                            class="iconfont icon-play nicebofang2"
                            :class="playIcon"
                            @click="togglePlaying"
                        ></i>
                        <i
                            class="iconfont icon-next nicexiayishou"
                            @click="nextSong"
                        ></i>
                    </div>
                    <audio
                        ref="audio"
                        :src="currentSong.url"
                        :muted="isMuted"
                        @timeupdate="updateTime"
                        @loadedmetadata="onLoadedmetadata"
                        @ended="audioEnd"
                    ></audio>
                    <!-- 音频进度条 -->
                    <div class="progress-wrap">
                        <p class="current-time">{{ utils.formatSecondTime(currentTime)}}</p>
                        <div class="progress-bar-wrap">
                            <el-slider
                                v-model="currentTime"
                                :show-tooltip="false"
                                :max="maxTime"
                                @change="progressChange($event)"
                                @mouseup.native="mouseupChangeTime"
                                :format-tooltip="realFormatSecond"
                            ></el-slider>
                        </div>
                        <p class="duration-time">
                            {{ utils.formatSecondTime(currentSong.duration) }}
                        </p>
                    </div>
                    <!-- 控制音量 -->
                    <div class="volume-wrap">
                        <i
                            class="iconfont volume-icon"
                            @click="changeMuted"
                            :class="mutedIcon"
                        ></i>
                        <div class="progress-bar">
                            <el-slider
                                v-model="volumeNum"
                                @change="changeVolume"
                                :show-tooltip="false"
                            ></el-slider>
                        </div>
                    </div>
                    <div class="tool">
                        <!-- 切换播放模式 -->
                        <i
                            class="iconfont"
                            :class="modeIcon"
                            @click="changeMode"
                        ></i>
                        <!-- 展开歌词 -->
                        <i
                            class="iconfont nicegeci32"
                            @click="toDetail()"
                        ></i>
                        <!-- 展开播放列表 -->
                        <i class="iconfont nicebofangliebiao24"></i>
                    </div>
                </div>

            </el-card>

        </div>
    </transition>
</template>

<script>
import { mapGetters, mapMutations, mapActions } from 'vuex'
import { playMode } from '@/common/playConfig'

function realFormatSecond(second) {
    var secondType = typeof second;

    if (secondType === 'number' || secondType === 'string') {
        second = parseInt(second);

        var hours = Math.floor(second / 3600);
        second = second - hours * 3600;
        var mimute = Math.floor(second / 60);
        second = second - mimute * 60;

        return ('0' + mimute).slice(-2) + ':' + ('0' + second).slice(-2)
    } else {
        return '00:00'
    }
}
export default {
    data() {
        return {
            currentTime: 0, // 音频当前播放时长
            maxTime: 0, // 音频最大播放时长
            volume: 0.1,
            volumeNum: 10, // 音量
            isMuted: false, // 是否静音
        }
    },
    created() {

    },
    mounted() {
    },
    computed: {
        // 播放暂停按钮
        playIcon() {
            return this.playing ? 'nicezanting1' : 'nicebofang2'
        },
        // 是否静音
        mutedIcon() {
            return this.isMuted ? 'nicejingyin1' : 'niceshengyin1'
        },
        // 播放模式
        modeIcon() {
            return this.mode === playMode.sequence
                ? 'nicexunhuanbofang24'
                : this.mode === playMode.loop
                    ? 'nicebofangqidanquxunhuan'
                    : 'nicebofangqisuijibofang'
        },
        ...mapGetters([
            'playList',
            'currentSong',
            'playing',
            'currentIndex',
            'mode',
            'sequenceList',
        ])
    },
    watch: {
        // 监听歌曲内容变化
        currentSong(newSong, oldSong) {
            if (!newSong.id || !newSong.url || newSong.id === oldSong.id) {
                return
            }
            this.$nextTick(() => {
                const audio = this.$refs.audio
                if (audio) {
                    audio.src = newSong.url
                    audio.volume = this.volume
                    audio.play()
                    this.getLyric()
                }
            })
        },
        // 监听播放状态
        playing(isPlaying) {
            this.$nextTick(() => {
                const audio = this.$refs.audio
                if (audio) {
                    isPlaying ? audio.play() : audio.pause()
                }

            })
        }
    },
    methods: {
        // 点击播放暂停
        togglePlaying() {
            this.setPlayingState(!this.playing)
        },
        // 上一首
        prevSong() {
            if (this.playList.length === 1) {
                this.loopSong()
                return
            } else {
                let index = this.currentIndex - 1
                if (index === -1) {
                    index = this.playList.length - 1
                }
                this.setCurrentIndex(index)
                if (!this.playing) {
                    this.togglePlaying()
                }
            }
        },
        // 下一首
        nextSong() {
            if (this.playList.length === 1) {
                this.loopSong()
                return
            } else {
                let index = this.currentIndex + 1
                if (index === this.playList.length) {
                    index = 0
                }
                this.setCurrentIndex(index)
                if (!this.playing) {
                    this.togglePlaying()
                }
            }
        },
        // 歌曲播放完成
        audioEnd() {
            // this.currentTime = 0
            if (this.mode === playMode.loop) {
                this.loopSong()
            } else {
                this.nextSong()
            }
        },
        // 监听播放时间改变
        updateTime(e) {
            this.currentTime = e.target.currentTime
            this.lyric.forEach((item, index) => {
                if (this.formatTime(item.time) <= this.formatTime(e.target.currentTime)) {
                    this.setLyricIndex(index)
                }
            })
        },

        // 获取音频长度
        onLoadedmetadata(res) {
            this.maxTime = parseInt(res.target.duration)

        },
        // 鼠标抬起改变当前时间点
        mouseupChangeTime() {
            this.progressChange(this.cacheCurrent)
        },
        // 拖动进度滚动条
        progressChange(value) {
            this.$refs.audio.currentTime = value >= 0 ? value : this.cacheCurrent;
            this.currentTime = value >= 0 ? value : this.cacheCurrent
        },
        // 自动播放触发
        realFormatSecond(second) {
            // console.log('自动播放触发', second);
            this.cacheCurrent = second;
            return realFormatSecond(second);
        },
        // 控制静音
        changeMuted() {
            if (this.isMuted) {
                this.isMuted = false
                this.$refs.audio.muted = false
            } else {
                this.isMuted = true
                this.$refs.audio.muted = true
            }
        },
        // 改变音量
        changeVolume(e) {
            this.volume = e / 100
            this.$refs.audio.volume = e / 100
        },
        // 切换播放模式
        changeMode() {
            const mode = (this.mode + 1) % 3
            this.setPlayMode(mode)
            let list = null
            if (mode === playMode.random) {
                list = this.utils.shuffle(this.sequenceList)
            } else {
                list = this.sequenceList
            }
            this.resetCurrentIndex(list)
            this.setPlayList(list)
        },
        // 重置当前播放歌曲序号
        resetCurrentIndex(list) {
            let index = list.findIndex(item => {
                return item.id === this.currentSong.id
            })
            this.setCurrentIndex(index)
        },
        // 单曲循环播放
        loopSong() {
            this.$refs.audio.play()
            this.setPlayingState(true)
        },

        // 获取歌词
        async getLyric() {
            let id = this.currentSong.id
            const { data: res } = await this.$api.getLyric(id)
            // console.log(res);
            if (res.code !== 200) {
                return this.message.error('获取歌词失败！');
            }
            let lrc = res.lrc.lyric
            this.lyric = []
            this.formatLyric(lrc)
            // console.log(lrc);
        },
        //传入初始歌词文本text
        formatLyric(text) {
            let arr = text.split("\n"); //原歌词文本已经换好行了方便很多，我们直接通过换行符“\n”进行切割
            let row = arr.length; //获取歌词行数
            for (let i = 0; i < row; i++) {
                let temp_row = arr[i]; //现在每一行格式大概就是这样"[00:04.302][02:10.00]hello world";
                let temp_arr = temp_row.split("]");//我们可以通过“]”对时间和文本进行分离
                let text = temp_arr.pop(); //把歌词文本从数组中剔除出来，获取到歌词文本了！
                //再对剩下的歌词时间进行处理
                temp_arr.forEach(item => {
                    let obj = {};
                    let time_arr = item.substr(1, item.length - 1).split(":");//先把多余的“[”去掉，再分离出分、秒
                    let s = parseInt(time_arr[0]) * 60 + Math.ceil(time_arr[1]); //把时间转换成与currentTime相同的类型，方便待会实现滚动效果
                    obj.time = s;
                    obj.text = text;
                    this.lyric.push(obj); //每一行歌词对象存到组件的lyric歌词属性里
                });
            }
            this.lyric.sort(this.sortRule); //由于不同时间的相同歌词我们给排到一起了，所以这里要以时间顺序重新排列一下
            this.setLyric(this.lyric); //把歌词提交到store里，为了重新进入该组件时还能再次渲染
        },
        sortRule(a, b) { //设置一下排序规则
            return a.time - b.time;
        },

        toDetail() {
            this.$router.push({
                name: 'playerDetail',
            })
        },
        // 格式化时间
        formatTime(interval) {
            interval = interval | 0
            const m = (interval / 60) | 0
            const s = interval % 60
            return `${this.utils.formatZero(m, 2)}:${this.utils.formatZero(s, 2)}`
        },
        ...mapMutations({
            setPlayingState: 'SET_PLAYING_STATE',
            setCurrentIndex: 'SET_CURRENT_INDEX',
            setPlayMode: 'SET_PLAY_MODE',
            setPlayList: 'SET_PLAYLIST',
            setLyric: 'SET_LYRIC',
            setLyricIndex: 'SET_LYRICINDEX'
        }),
        ...mapActions([
            'selectPlay',
            'pausePlay'
        ])
    }
}
</script>
<style lang="less" scoped>
.player-bar {
    position: fixed;
    bottom: 0;
    right: 0;
    left: 0;
    z-index: 2;
    .box-card {
        width: 100%;
        height: 75px;
        .container {
            height: 100%;
            display: flex;
            align-items: center;
            padding: 5px 20px;
            margin: 0;
            .avatar {
                width: 60px;
                height: 60px;
                min-width: 60px;
                margin-right: 30px;
                box-sizing: border-box;
                img {
                    width: 100%;
                    height: 100%;
                    border-radius: 5px;
                }
                &:hover {
                    cursor: pointer;
                }
            }

            .info {
                width: 13%;
                .name,
                .singer {
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .name {
                    font-size: 14px;
                    color: #333333;
                    font-weight: bold;
                    &:hover {
                        color: #fa2800;
                        cursor: pointer;
                    }
                }
                .singer {
                    margin-top: 10px;
                    font-size: 12px;
                    color: #666666;
                }
            }

            .player-btn {
                display: flex;
                align-items: center;
                i {
                    cursor: pointer;
                    &:active {
                        opacity: 0.8;
                    }
                }

                .icon-prev {
                    font-size: 40px;
                }
                .icon-play {
                    font-size: 60px;
                    margin: 0 10px;
                }
                .icon-next {
                    font-size: 40px;
                }
                .icon-prev,
                .icon-play,
                .icon-next {
                    &:hover {
                        color: #fa2800;
                        cursor: pointer;
                    }
                }
            }
            i {
                &:hover {
                    color: #fa2800;
                    cursor: pointer;
                }
            }
            .progress-wrap {
                width: 380px;
                height: 100%;
                display: flex;
                align-items: center;
                margin: 0 40px;
                p {
                    font-size: 14px;
                }
                .progress-bar-wrap {
                    margin: 0 15px;
                    width: 200px;
                }
            }
            .volume-wrap {
                width: 200px;
                display: flex;
                align-items: center;
                .volume-icon {
                    font-size: 25px;
                    font-weight: bold;
                    cursor: pointer;
                    &:hover {
                        color: #fa2800;
                        cursor: pointer;
                    }
                }
                .progress-bar {
                    margin: 0 15px;
                    width: 100%;
                }
            }
            .tool {
                margin-left: 40px;
                .iconfont {
                    font-size: 26px;
                    margin: 0 15px;
                    cursor: pointer;

                    &:active {
                        opacity: 0.7;
                    }

                    &.icon-like {
                        font-size: 26px;
                    }
                }
            }
        }
    }
}
</style>